//
//  NSOutputStreamViewController.m
//  StudyDemo
//
//  Created by 赵忠鹏 on 2018/5/4.
//  Copyright © 2018年 zhaozhongpeng. All rights reserved.
//

#import "NSOutputStreamViewController.h"

@interface NSOutputStreamViewController ()<NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *outputProgress;
@property (weak, nonatomic) IBOutlet UITextView *outputTextView;

@property (nonatomic,assign) CGFloat totalLength;

@property (nonatomic,copy) NSString *fileName;

@property (nonatomic,copy) NSString *filePath;

@property (nonatomic,assign) CGFloat currentLength;
// 输出流
@property (nonatomic,strong) NSOutputStream *stream;


@end

@implementation NSOutputStreamViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_03.mp4"]];
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    self.totalLength = response.expectedContentLength; // 文件总大下
    
    self.fileName = response.suggestedFilename; // 服务器推荐名字
    
    // 2.拼接文件全路径
    self.filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:self.fileName];
    self.outputTextView.text = self.filePath;
    
    NSLog(@" 路径 - %@",self.filePath);
    
    // 创建输出流
    /*
     第一个参数：二进制文件写到哪的路径
     第二个参数：append - YES 追加数据  NO 覆盖数据
     */
    self.stream = [NSOutputStream outputStreamWithURL:[NSURL fileURLWithPath:self.filePath] append:YES];
    
    // open 一调用就会像文件中写数据，如果文件不存在就会创建
    [self.stream open];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    // 使用 输出流 写数据
    /*
     第一个参数：需要写入的数据
     第二个参数：写入数据的长度
     */
    [self.stream write:data.bytes maxLength:data.length];
    
    self.currentLength += data.length;
    
    self.outputProgress.progress = 1.0 * (self.currentLength/self.totalLength);
    
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [self.stream close];
    self.stream = nil;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
}


@end
